package start.demo01.fileIO;

import org.junit.Test;

import java.io.*;
import java.util.Random;

public class RandomFile {
    /*
    * RandomAccessFile支持随机访问，可以调转到文件的任意位置
    * 写：在任意位置追加内容
    * 包含一个指针，用于标识当前读写位置，新文件对象指针位于文件头（0）
    * 当读n个字节后，指针对应后移n
    * long getFilePointer()返回当前指针位置
    * void seek(long pos);将文件记录指针定位到pos处
    * RandomAccessFile(File file,String mode)
    * setLength(long newLength) 设置此文件的长度。以字节为单位
    *
    * mode表示访问模式
    * “r”：以只读方式打开
    * “rw”：以读/写方式打开，如果文件不存在则尝试创建
    * “rws”:以读/写方式打开，相较于“rw”,还要求对文件内容及元数据的每个更新同步写入到底层存储设备
    * "rwd":以读/写方式打开，相较于“rw”,还要求对文件内容每个更新同步写入到底层存储设备
    * */
    public static byte[] getBytes(char[] chars) {
        byte [] result = new byte[chars.length];
        for(int i=0;i<chars.length;i++){
            result[i] = (byte) chars[i];
        }
        return result;
    }
    @Test
    public void t0(){
        //jdk1.8
        File f=new File("C:\\Users\\wangcj\\Desktop\\tmp\\总结.txt");
        String ls=System.getProperty("line.separator");
        try(RandomAccessFile raf=new RandomAccessFile(f,"rw")){
            long length=raf.length();
            long readpointer;
            long writepointer;
            long delLen;
            String line;
            while((line=raf.readLine())!=null){
                line=new String(getBytes(line.toCharArray()));
                long pointer = raf.getFilePointer();
                writepointer=pointer-line.length()-ls.length();//行首位置

            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws IOException {
        int count =3;
        long chunkSize=200;
        for(int i=0;i<count;i++) {
            File confFile = new File("conf.txt");
            if(!confFile.exists())
                confFile.createNewFile();
            RandomAccessFile accessConfFile = new RandomAccessFile(confFile, "rw");
            accessConfFile.setLength(count);
            accessConfFile.seek(i);
            //将指定的字节写入此文件。 写入从当前文件指针开始。
            accessConfFile.write(127);
            accessConfFile.close();
            File tmpFile = new File("tmp.txt");
            if(!tmpFile.exists())
                tmpFile.createNewFile();
            RandomAccessFile accessTmpFile = new RandomAccessFile(tmpFile, "rw");
            long offset = chunkSize * (long) i;
            accessTmpFile.seek(offset);
            accessTmpFile.write(("ce_shi"+i).getBytes());
            accessTmpFile.close();
            byte[] completeList=new byte[(int)confFile.length()];
            FileInputStream inputStream = new FileInputStream(confFile);
            inputStream.read(completeList,0,(int)confFile.length());
            inputStream.close();
            byte isComplete = 127;
            for (int c = 0; c < completeList.length && isComplete == 127; ++c) {
                isComplete &= completeList[c];//检查文件是否完全上传
            }
            if (isComplete != 127) {//此分片上传成功，但未完成整体上传
                System.out.println("文件上传成功");
            }
        }
    }
    public static void test(){
        try(RandomAccessFile raf=new RandomAccessFile(new File("das.txt"),"rw");
            ){
            //raf.setLength(300);
            System.out.println("长度"+raf.length());
            String s=new String("如果文件不存在则尝试创建".getBytes());
            System.out.println("当前指针位置"+raf.getFilePointer());
//            raf.seek(12);
//            byte[] buffer=new byte[20];
//            int len=-1;
//            while((len=raf.read(buffer))!=-1){
//                System.out.println(new String(buffer,0,len));
//            }
            //raf.seek(raf.length());//指针移动到文件末尾
            raf.write(s.getBytes());
            raf.writeInt(13);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @Title: removeFileLine
     * @Description: TODO(该方法为从文件开头删除前n行)
     * @param: @param file 文件
     * @param: @param lineNum 删除的行行数
     * @param: @throws IOException
     * @return: void
     * @throws
     */
    public void removeFileLine(File file, int lineNum) throws IOException {
        try(RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
            // Initial write position.
            // 写文件的位置标记,从文件开头开始,后续读取文件内容从该标记开始
            long writePosition = raf.getFilePointer();
            System.out.println("writePosition:"+writePosition);
            for (int i = 0; i < lineNum; i++) {
                String line = raf.readLine();
                if (line == null) {
                    break;
                }
            }
            // Shift the next lines upwards.
            // 读文件的位置标记,写完之后回到该标记继续读该行
            long readPosition = raf.getFilePointer();
            System.out.println("readPosition:"+readPosition);
            // 利用两个标记,
            byte[] buff = new byte[1024];
            int n;
            while (-1 != (n = raf.read(buff))) {
                raf.seek(writePosition);
                raf.write(buff, 0, n);
                readPosition += n;
                writePosition += n;
                raf.seek(readPosition);
            }
            raf.setLength(writePosition);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
